package com.year.shiyi.common.utils.oauth2;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.year.shiyi.entity.mybatis.SysUserEntity;
import com.year.shiyi.entity.mybatis.SysUserTokenEntity;
import com.year.shiyi.service.ShiroService;
import com.year.shiyi.service.SysUserService;
import com.year.shiyi.service.SysUserTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author shiyi on 2021/2/23 16:19
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private SysUserService sysUserService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Toekn;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        Set<String> permsSet = shiroService.getUserPermissions(user.getUserId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        // 根据token查询用户信息
        SysUserTokenEntity tokenEntity = sysUserTokenService.getOne(new QueryWrapper<SysUserTokenEntity>().eq("token", accessToken));
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        SysUserEntity user = sysUserService.getOne(new QueryWrapper<SysUserEntity>()
                .eq("user_id", tokenEntity.getUserId())
                .eq("status", 0)
        );
        if (user == null) {
            throw new LockedAccountException("账号已被锁定，请联系管理员");
        }
        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
